package com.example.matchandroiddevices.test;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UsbSerialCommunicator {
    private static final String TAG = "UsbSerialCommunicator";

    private Context context;
    private UsbManager usbManager;
    private UsbSerialPort serialPort;
    private SerialInputOutputManager serialIoManager;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private SerialDataListener dataListener;

    // 接收数据的监听器接口
    public interface SerialDataListener {
        void onDataReceived(byte[] data);
        void onError(Exception e);
    }

    public UsbSerialCommunicator(Context context, SerialDataListener listener) {
        this.context = context;
        this.usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        this.dataListener = listener;
    }

    /**
     * 查找可用的USB串口设备
     */
    public List<UsbSerialDriver> findUsbSerialDevices() {
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
        Log.d(TAG, "Found " + availableDrivers.size() + " USB serial devices");

        for (UsbSerialDriver driver : availableDrivers) {
            UsbDevice device = driver.getDevice();
            Log.d(TAG, String.format("USB Serial Device: %s (VID:%04X, PID:%04X)",
                    device.getDeviceName(),
                    device.getVendorId(),
                    device.getProductId()));
            Log.d(TAG, "  Ports: " + driver.getPorts().size());
        }

        return availableDrivers;
    }

    /**
     * 连接到指定的USB串口设备
     */
    public boolean connect(UsbSerialDriver driver, int baudRate) {
        if (driver == null) {
            Log.e(TAG, "Cannot connect to null driver");
            return false;
        }

        UsbDevice device = driver.getDevice();

        // 检查权限
        if (!usbManager.hasPermission(device)) {
            Log.e(TAG, "No permission to access device");
            return false;
        }

        // 打开连接
        UsbDeviceConnection connection = usbManager.openDevice(device);
        if (connection == null) {
            Log.e(TAG, "Failed to open device connection");
            return false;
        }

        try {
            // 默认使用第一个串口
            serialPort = driver.getPorts().get(0);
            serialPort.open(connection);
            serialPort.setParameters(baudRate,
                    UsbSerialPort.DATABITS_8,
                    UsbSerialPort.STOPBITS_1,
                    UsbSerialPort.PARITY_NONE);

            Log.d(TAG, "Serial connection opened with baudrate: " + baudRate);
            // 设置IO管理器处理数据读写
            SerialInputOutputManager.Listener listener = new SerialInputOutputManager.Listener() {
                @Override
                public void onNewData(byte[] data) {
                    if (dataListener != null) {
                        dataListener.onDataReceived(data);
                    }
                }

                @Override
                public void onRunError(Exception e) {
                    Log.e(TAG, "Serial communication error", e);
                    if (dataListener != null) {
                        dataListener.onError(e);
                    }
                }
            };

            serialIoManager = new SerialInputOutputManager(serialPort, listener);
            executor.submit(serialIoManager);

            return true;

        } catch (IOException e) {
            Log.e(TAG, "Error opening serial port", e);
            disconnect();
            if (dataListener != null) {
                dataListener.onError(e);
            }
            return false;
        }
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        if (serialIoManager != null) {
            serialIoManager.stop();
            serialIoManager = null;
        }

        if (serialPort != null) {
            try {
                serialPort.close();
            } catch (IOException e) {
                Log.e(TAG, "Error closing serial port", e);
            }
            serialPort = null;
        }
    }

    /**
     * 发送数据
     */
    public void sendData(byte[] data) {
        if (serialPort != null) {
            try {
                serialPort.write(data, 1000);
                Log.d(TAG, "Sent " + data.length + " bytes");
            } catch (IOException e) {
                Log.e(TAG, "Error sending data", e);
                if (dataListener != null) {
                    dataListener.onError(e);
                }
            }
        } else {
            Log.e(TAG, "Cannot send data, serial port not opened");
        }
    }
}
